package org.onionframework.persistence.dao.expression;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.onionframework.core.Onion;
import org.onionframework.core.config.SystemConfig;
import org.onionframework.persistence.dao.escape.DatabaseEscapeUtils;

public class EscapedLikeExpression extends SimpleExpression {

	private static final long serialVersionUID = -8277235093414167691L;
	
	public static final String DIALECT_HIBERNATE;
	
	private static boolean escape = false;
	private static boolean appendEscape = false;
	
	static{
		SessionFactory sessionFactory = Onion.getBean(SessionFactory.class);
		if(sessionFactory instanceof SessionFactoryImplementor)
			DIALECT_HIBERNATE = ((SessionFactoryImplementor)sessionFactory).getDialect().getClass().getName();
		else
			throw new RuntimeException("hibernate 方言获取失败");
		
		appendEscape = SystemConfig.Config.getBoolean("onion.core.auto_escape_like",true)
			&& (DIALECT_HIBERNATE.indexOf("Oracle") > -1
			|| DIALECT_HIBERNATE.indexOf("HSQL") > -1);
		
		escape = SystemConfig.Config.getBoolean("onion.core.auto_escape_like",true);
	}
	
	public EscapedLikeExpression(String propertyName, Object value) {
		super(propertyName, escape ? DatabaseEscapeUtils.escape((String)value) : value, " like ");
	}
	
	public EscapedLikeExpression(String propertyName, Object value, boolean ignoreCase) {
		super(propertyName, escape ? DatabaseEscapeUtils.escape((String)value) : value, " like ", true);
	}

	@Override
	public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
		throws HibernateException {
		String result = super.toSqlString(criteria, criteriaQuery);
		if(appendEscape)
			result = result + " escape '/'";
		return result;
	}

}
